package com.bo.wei.chen.mybatis.model;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @author hsjry
 */
@Getter
@AllArgsConstructor
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum EnumBool implements IEnum, Serializable {
    /** 否 */
    NO("0", "否"),
    /** 是 */
    YES("1", "是");

    /** 编码 */
    private String code;
    /** 描述 */
    private String description;

    public static EnumBool find(String code) {
        return Arrays.stream(EnumBool.values()).filter(input -> input.getCode().equals(code)).findFirst().orElse(null);
    }

    /**
     * 用于保存所有的枚举值
     */
    private static Map<String, EnumBool> RESOURCE_MAP = Stream
        .of(EnumBool.values())
        .collect(Collectors.toMap(EnumBool::getCode, Function.identity()));

    /**
     * 枚举反序列话调用该方法
     *
     * @param jsonNode
     * @return
     */
    @JsonCreator
    public static EnumBool des(final JsonNode jsonNode) {
        return Optional
            .ofNullable(RESOURCE_MAP.get(jsonNode.get("type").asText()))
            .orElseThrow(() -> new IllegalArgumentException(jsonNode.get("type").asText()));
    }
}
